package com.sh.sales.happysales.app.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * Created by zhouyucheng on 2017/9/14.
 */

public class TimerUtil {

    private String TAG = "TimerUtil";
    public static final int COUNT_DOWN_TIME = 60;

    public static final String MESSAGE_EXTRAL = "s 后重发";

    private volatile static TimerUtil mInstance;

    final Context mContext;

    private OnTimeListener mOnTimerListener;

    public int leaveTime;
    //用于点播播放器付费倒计时
    public int periodTime = 1000;


    public int getPeriodTime() {
        return periodTime;
    }


    public void setPeriodTime(int periodTime) {
        this.periodTime = periodTime;
    }

    private Handler handler;

    public TimerUtil(Context mContext) {
        this.mContext = mContext;
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        if (mOnTimerListener != null) {
                            leaveTime--;
                            if (leaveTime > 0) {
                                mOnTimerListener.onTime(leaveTime);
                                handler.sendEmptyMessageDelayed(1, periodTime);
                            } else {
                                mOnTimerListener.onEnd();
                            }
                        } else {
                            Log.i(TAG, "handleMessage: mOnTimerListener is null");
                        }
                        break;

                    default:
                        break;
                }

            }

        };
    }

    public interface OnTimeListener {

        void onTime(int second);

        void onEnd();

    }

    public synchronized static TimerUtil getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new TimerUtil(context);
        }
        return mInstance;
    }

    public void startCountTime(int time) {
        if (!handler.hasMessages(1)) {
            leaveTime = time;
            handler.sendEmptyMessage(1);
        }
    }

    public void startCountTime() {
        startCountTime(COUNT_DOWN_TIME);
    }

    public void setOnTimeListener(OnTimeListener onTimeListener) {
        this.mOnTimerListener = onTimeListener;
    }

    public void StopTimer() {
        while (handler.hasMessages(1)) {
            handler.removeMessages(1);
        }
//		mOnTimerListener = null;
        periodTime = 1000;
    }
}
